import React, { useContext, useRef } from "react";
import update from 'immutability-helper'

import { useSortable } from "@dnd-kit/sortable";
import { DesignFrameworkContext } from "./DesignFramework";
import DesignToolbar from "./DesignToolbar";
import useDesignActions from "./useDesignActions";
import { DropTargetMonitor, useDrag, useDrop } from "react-dnd";
import { SchemaFieldContext } from "../core/SchemaField";
const style = {
  border: '1px dashed gray',
  padding: '0.5rem 1rem',
  // marginBottom: '.5rem',
  // backgroundColor: 'white',
  cursor: 'move',
}
function selectBackgroundColor(isActive: boolean, canDrop: boolean) {
  // if (isActive) {
  //   return 'darkgreen'
  // } else if (canDrop) {
  //   return '#fff'
  // } else {
  //   return '#222'
  // }
  return '#fff'
  // return canDrop?'red':'yellow'
}

const DesignDecorator = ({ parentSchema, sortable, index, children, item }) => {

  const { updateDesign } = useDesignActions();
  const ref = useRef<HTMLDivElement>(null)

  const { setCurrentDesign, onDrop, currentDesign } = useContext(
    DesignFrameworkContext
  );
  const { items } = useContext(
    SchemaFieldContext
  );
  // const [collectedProps, drop] = useDrop(() => ({
  //   accept: 'accept'
  // }))
  // const {
  //   setNodeRef,
  //   listeners,
  //   attributes,
  //   isDragging,
  //   isSorting,
  //   over,
  //   overIndex,
  //   transform,
  //   transition,
  // } = useSortable({
  //   id: item._id,
  // });
  const [{ isOver, canDrop }, drop] = useDrop(
    () => ({
      accept: 'BOX',
      hover(_item: any, monitor) {
        if (!ref.current) {
          return
        }
        setCurrentDesign({})
      
        // // // 拖动的索引
        const dragIndex = _item.$index
        // //   // 放到
        const hoverIndex = index
        const _items = items.properties['x-component-props']['items']
        console.log('item', item.index, JSON.stringify(item))
        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
          return
        }
        // Determine rectangle on screen
        const hoverBoundingRect = ref.current?.getBoundingClientRect()

        // Get vertical middle
        const hoverMiddleY =
          (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2

        // Determine mouse position
        const clientOffset = monitor.getClientOffset()

        // Get pixels to the top
        const hoverClientY = (clientOffset as any).y - hoverBoundingRect.top

        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%

        // Dragging downwards
        if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
          return
        }

        // Dragging upwards
        if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
          return
        }

        // Time to actually perform the action
        // moveCard(dragIndex, hoverIndex)
        // console.log('component=',{dragIndex,hoverIndex})
        items.properties['x-component-props']['items'] = update(_items, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, _items[dragIndex] as any],
          ],
        })
        // console.log('component=',{dragIndex,hoverIndex,_items},items.properties['x-component-props'])

        updateDesign()
        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        _item.$index = hoverIndex

      },
      collect: (monitor: DropTargetMonitor) => ({
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
      }),
    }),
    [onDrop, item, items, parentSchema],
  )
  const [{ isDragging }, drag] = useDrag({
    type: 'BOX',
    item: () => {
      item.$index = index
      return item
    },
    collect: (monitor: any) => ({
      isDragging: monitor.isDragging(),
    }),
  }, [item])

  // const style: React.CSSProperties = {
  //   // transform: CSS.Transform.toString(transform),
  //   transform: `translate3d(${transform?.x || 0}px, ${transform?.y || 0}px, 0)`,
  //   // border: isDragging ? '1px dashed  red' : '1px dashed  #36cfc9',
  //   // margin: 5,
  //   // backgroundColor:isOver&&!isDragging&&item.isContainer?'red':'',
  //   // position:'absolute',
  //   // width:'100%',
  //   // zIndex:isDragging?9900:98,
  //   transition,
  // };
  const isActive = canDrop && isOver

  const backgroundColor = selectBackgroundColor(isActive, isOver)

  if (item.isPageContainer) {
    return (
      <div
        data-id={item._id}
        // ref={drop}
        style={{ backgroundColor, position: "relative", height: '100%' }}
        onClick={(e) => {
          setCurrentDesign(item);
          e.preventDefault()
          e.stopPropagation()
          updateDesign();
        }}
      >
        {currentDesign._id == item._id ? <DesignToolbar disabledActions /> : null}
        {children}
      </div>
    );
  }
  const opacity = isDragging ? 0 : 1
  drag(drop(ref))
  return (
    <div
      ref={sortable ? ref : null}
      onClick={(e) => {
        setCurrentDesign(item);
        updateDesign();
        e.stopPropagation()
        e.preventDefault()
      }}
      style={{ ...style, backgroundColor, opacity, position: 'relative' }}
    // className={
    //   currentDesign._id == item._id
    //     ? "deigin-item deigin-item-active"
    //     : "deigin-item"
    // }
    // ref={setNodeRef}
    // {...listeners}
    // onMouseDown={(e) => {
    //   setCurrentDesign(item);
    //   updateDesign();
    //   e.stopPropagation();
    //   listeners?.onMouseDown(e);
    // }}
    // style={style}
    >
      {currentDesign._id == item._id ? <DesignToolbar item={item} /> : null}

      {children}
    </div>
  );
};
export default DesignDecorator;
